package ui;

import unit.Field;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

/**
 * 메인맵 클래스
 */
public class MainMap extends JPanel
{
    private Field field;

	private BufferedImage buffer;

	private static int scrollPos = 0;
	private JFrame owner;
	private MiniMap listener;

	private int mouseX;
	private int mouseY;

	public MainMap(JFrame owner)
	{
		super();
		this.owner = owner;
        field = new Field(this);
		field.addUnit(field.new Tank(this, 10, 241));
		buffer = new BufferedImage(5120 + 10, 618 + 10, BufferedImage.TYPE_INT_ARGB);
		buffer.createGraphics();

		setBounds(0, 150, 1024, 618);

		// 목표물을 추가한다.
		for (int i = 0; i < 30; i++)
			field.addUnit(field.new Target());

		addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent event)
			{
				if (event.getButton() == MouseEvent.BUTTON1)
				{

				}
				else if (event.getButton() == MouseEvent.BUTTON3)
				{

				}
			}
		});

		new Thread()
		{
			@Override
			public void run()
			{
				while (true)
				{
					try
					{
						if (MainMap.this.owner.isActive() == false)
							continue;

						int x = MainMap.this.owner.getX();
						int y = MainMap.this.owner.getY();
						PointerInfo pt = MouseInfo.getPointerInfo();
						if (pt.getLocation().x - x >= 1000)
							scrollPos = Math.min(4096, scrollPos + 10);

						else if (pt.getLocation().x - x <= 10)
							scrollPos = Math.max(0, scrollPos - 10);

						field.adjustAllUnits();
						repaint();
						listener.repaint();

						sleep(10);
					}
					catch (InterruptedException e)
					{
					}
				}
			}
		}.start();
	}

	@Override
	public void paint(Graphics g)
	{
		Graphics bufferGraphics = buffer.getGraphics();
		bufferGraphics.setColor(Color.WHITE);
		bufferGraphics.fillRect(0, 0, buffer.getWidth(), buffer.getHeight());

		// 맵과 유닛들을 출력한다.
		field.draw(bufferGraphics);

		// 미니맵에 빨간 테두리를 그린다.
		bufferGraphics.setColor(Color.RED);
		((Graphics2D) bufferGraphics).setStroke(new BasicStroke(10));
		bufferGraphics.drawRect(scrollPos, 0, getWidth(), getHeight());

		g.drawImage(buffer, -scrollPos - 10, -10, null);
	}

	public BufferedImage getBuffer()
	{
		return buffer;
	}

	public void setListener(MiniMap listener)
	{
		this.listener = listener;
	}

	public void scrollTo(int x)
	{
		scrollPos = x;
		scrollPos = Math.min(4096, scrollPos + 10);
		scrollPos = Math.max(0, scrollPos - 10);
		repaint();
	}

	public static int getScrollPos()
	{
		return scrollPos;
	}
}